package com.yuneec.fly.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;

/**
 * Created by jw.gu on 2016/6/17.
 */
public class BitmapUtils {

    public static BitmapDrawable getBitmapDrawableWithAngle(Context context, int resourceId, int length, float angle) {
        Bitmap bm = BitmapFactory.decodeResource(context.getResources(), resourceId);
        if (angle % 360 == 0) {
            return new BitmapDrawable(bm);
        }
        Matrix m = new Matrix();
        m.setRotate(angle, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2);
        Bitmap bm1 = null;
        try {
            bm1 = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), m, true);
            bm.recycle();
        } catch (OutOfMemoryError ex) {
            ex.printStackTrace();
        }
        if (bm1 != null) {
            return new BitmapDrawable(centerSquareScaleBitmap(bm1, (angle % 90 == 0) ? length : length - 2));
        }
        return null;
    }

    /**
     * @param bitmap     原图
     * @param edgeLength 希望得到的正方形部分的边长
     * @return 缩放截取正中部分后的位图。
     */
    public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
        if (null == bitmap || edgeLength <= 0) {
            return null;
        }

        Bitmap result = bitmap;
        int widthOrg = bitmap.getWidth();
        int heightOrg = bitmap.getHeight();

        if (widthOrg > edgeLength && heightOrg > edgeLength) {

            //从图中截取正中间的正方形部分。
            int xTopLeft = (widthOrg - edgeLength) / 2;
            int yTopLeft = (heightOrg - edgeLength) / 2;

            try {
                result = Bitmap.createBitmap(bitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
                bitmap.recycle();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        return result;
    }
}
